// const game = {
//   lastTime: Date.now(),
//   dt: 0,
// };
// setInterval(() => {
//   const now = Date.now();
//   game.dt = now - game.lastTime;
//   game.lastTime = now;
//   console.log(game.dt);
// }, 2);
import * as WebSocket from 'ws';
import {io} from "./io";
import {Context} from "./context";
import {contextManager, matchManager, roomManager} from "./manager";

const wss = new WebSocket.Server({port: 3001});

let playersInfo = {};

wss.on('connection', function connection(ws) {
  const ctx = contextManager.createContext(ws);
  // ws.id = ctx.id;
  // ws.
  ws.on('message', function incoming(message: any) {
    io.onmessage(JSON.parse(message), contextManager.getCtxByWs(ws));
  });
});

io.on('timeSync', function (data, ctx: Context) {
  ctx.emit('timeSync', {time: data.time})
});

io.on('match', function (data: { uid: number, name: string }, ctx: Context) {
  ctx.user = data;
  matchManager.match(ctx);
});


io.on('pos', function (data: { r, x, y }, ctx: Context) {
  playersInfo[ctx.user.uid] = data;
});

setInterval(() => {
  if (roomManager.room && roomManager.room.isStart) {
    roomManager.room.broadcast('pos', playersInfo)
  }
});